/**
 * @Project:
 * @Author: wanghong
 * @Date: 2019年03月13日
 * @Copyright: ©2019-2028 www.xfxb.net Inc. All rights reserved.
 */
package com.carryking.http.proxy.ssr.utils;

import com.carryking.http.proxy.ssr.entity.HostInfo;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.URL;

/**
 * @author wanghong
 * @date 2019年03月13日
 */
public class HostParseUtils {

    private final static Logger log = LoggerFactory.getLogger(HostParseUtils.class);

    private final static String https = "https://";

    public static HostInfo parseHost(String urlString) {
        try {
            int defaultPort = StringUtils.startsWith(urlString, https) ? 443 : 80;
            URL url = new URL(urlString);
            log.info("url={}",new Gson().toJson(url));
            HostInfo hostInfo = new HostInfo();
            hostInfo.setHost(url.getHost());
            hostInfo.setPort(url.getPort());
            if (hostInfo.getPort() == null) {
                hostInfo.setPort(defaultPort);
            }
            int n = StringUtils.indexOf(hostInfo.getHost(), ":");
            if (n != -1) {
                String host = StringUtils.substring(hostInfo.getHost(), 0, n);
                hostInfo.setHost(host);
            }
            InetAddress address = InetAddress.getByName(hostInfo.getHost());
            hostInfo.setIp(address.getHostAddress());
            return hostInfo;
        } catch (Exception e) {
            log.error("解析host异常:{}",urlString,e);
        }
        return null;
    }


}
